package com.xyyl.patient.core.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xyyl.patient.core.constant.HttpStatusEnum;

/**
 * @ClassName: ResponseBodyResult
 * @Description: response result
 * @author chen
 * @date 2017年8月17日
 *
 */
public class ResponseBodyResult {

	private static final Logger logger = LogManager.getLogger(ResponseBodyResult.class);

	public static <T> JSONObject success(String msg, T data) {
		return returnObject(HttpStatusEnum.SUCCESS.getCode(), msg, HttpStatusEnum.SUCCESS.getDescription(), data);
	}

	public static <T> JSONObject success(T data) {
		return returnObject(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMsg(),
				HttpStatusEnum.SUCCESS.getDescription(), data);
	}

	public static <T> JSONObject success() {
		return returnObject(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMsg(),
				HttpStatusEnum.SUCCESS.getDescription());
	}

	public static <T> JSONObject success(String msg) {
		return returnObject(HttpStatusEnum.SUCCESS.getCode(), msg, HttpStatusEnum.SUCCESS.getDescription());
	}

	public static JSONObject fail(String msg) {
		return returnObject(HttpStatusEnum.SERVER_FAIL.getCode(), msg, HttpStatusEnum.SERVER_FAIL.getDescription());
	}

	public static JSONObject fail(String code, String msg) {
		return returnObject(code, msg, HttpStatusEnum.SERVER_FAIL.getDescription());
	}

	public static JSONObject error(String msg, Exception e) {
		return returnObject(msg, e);
	}

	private static <T> JSONObject returnObject(String code, String msg, String memo, T data) {
		if (logger.isDebugEnabled()) {
			logger.info(msg);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", code);
		jsonObject.put("operateTime", System.currentTimeMillis());
		jsonObject.put("returnmemo", memo);
		jsonObject.put("msg", msg);
		jsonObject.put("result", data);
		return jsonObject;
	}

	private static <T> JSONObject returnObject(String code, String msg, String memo) {
		if (logger.isDebugEnabled()) {
			logger.info(msg);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", code);
		jsonObject.put("operateTime", System.currentTimeMillis());
		jsonObject.put("returnmemo", memo);
		jsonObject.put("msg", msg);
		return jsonObject;
	}

	private static <T> JSONObject returnObject(String msg, Exception exception) {
		logger.error(msg, exception.toString());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", HttpStatusEnum.SERVER_ERROR.getCode());
		jsonObject.put("operateTime", System.currentTimeMillis());
		jsonObject.put("returnmemo", HttpStatusEnum.SERVER_ERROR.getDescription());
		jsonObject.put("msg", msg);
		return jsonObject;
	}

	@Override
	public String toString() {
		String json = JSON.toJSONString(this);
		return json;
	}

}
